package com.lcc.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.lcc.common.constant.ProductConstant;
import com.lcc.common.to.SkuHasStockTo;
import com.lcc.common.to.SkuReductionTo;
import com.lcc.common.to.SpuBoundsTo;
import com.lcc.common.to.es.SkuEsModel;
import com.lcc.common.utils.R;
import com.lcc.gulimall.product.entity.*;
import com.lcc.gulimall.product.feign.CouponFeignService;
import com.lcc.gulimall.product.feign.SearchFeignService;
import com.lcc.gulimall.product.feign.WareFeignService;
import com.lcc.gulimall.product.service.*;
import com.lcc.gulimall.product.vo.sku.SpuSaveVo;
import com.lcc.gulimall.product.vo.sku.*;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lcc.common.utils.PageUtils;
import com.lcc.common.utils.Query;

import com.lcc.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
@Slf4j
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    SpuInfoDescService spuInfoDescService;
    @Autowired
    SpuImagesService spuImagesService;
    @Autowired
    ProductAttrValueService productAttrValueService;
    @Autowired
    AttrService attrService;
    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    BrandService brandService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    WareFeignService wareFeignService;
    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存商品，大保存，要保存很多东西，需要加上事务注解
     * @param vo
     */
    @GlobalTransactional
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1.保存SPU基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);

        //2.保存SPU描述图片pms_spu_info_desc
        List<String> spuDecript = vo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", spuDecript));
        spuInfoDescService.save(spuInfoDescEntity);

        //3.保存SPU图片集pms_spu_images
        List<String> images = vo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), images);

        //4.保存SPU的规格参数pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> attrValueEntities = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(attr.getAttrId());
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(attrValueEntities);

        //5.保存SPU积分信息 跨库sms:sms_spu_bounds
        Bounds bounds = vo.getBounds();
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds, spuBoundsTo);
        spuBoundsTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundsTo);
        if(r.getCode() != 0){
            log.error("远程保存spu积分信息失败");
        }
        //5.保存当前SPU对应的所有SKU信息
        // 5.1 sku基本信息 pms_sku_info
        //List<Skus> skus = vo.getSkus();
        //if(skus != null && skus.size() > 0){
        List<Skus> skus = null;
        if(skus.size() > 0){
            skus.forEach(item->{
                String defaultImg = "";
                for(Images img : item.getImages()){
                    if(img.getDefaultImg() == 1){
                        defaultImg = img.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.save(skuInfoEntity);
                Long skuId = skuInfoEntity.getSkuId();
                // 5.2 sku图片信息 pms_sku_images
                List<SkuImagesEntity> skuImagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity->{
                    //返回true就是需要
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntities);
                // 5.3 sku的销售属性信息 pms_sku_sale_attr_value
                List<Attr> attrs = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, attrValueEntity);
                    attrValueEntity.setSkuId(skuId);
                    return attrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
                // 5.4 sku的优惠、满减、会员价格、积分等信息：需要操作sms数据库:sms_sku_ladder、sms_sku_full_reduction、sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if(skuReductionTo.getFullCount() > 0 && skuReductionTo.getFullPrice().compareTo(BigDecimal.ZERO) == 1){
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if(r1.getCode() != 0){
                        log.error("远程保存sku优惠信息失败");
                    }
                }

            });
        }


    }

    /**
     * 商品上架
     * @param spuId
     */
    @Override
    public void up(Long spuId) {
        //1.查出当前spu对应的所有sku信息，品牌名
        List<SkuInfoEntity> upSkuInfos = skuInfoService.getSkusBySpuId(spuId);

        //查出当前sku所有规格属性 只查可以被用来检索的规格属性 由于所有sku规格属性相同 所以查一遍即可
        List<ProductAttrValueEntity> attrValueEntities = productAttrValueService.listForSpu(spuId);
        //挑出所有可检索的属性
        List<Long> attrIdList = attrValueEntities.stream().map(item -> item.getAttrId()).collect(Collectors.toList());
        List<Long> searchAttrIdList = attrService.selectSearchAttrIdList(attrIdList);
        Set<Long> attrIdSet = new HashSet<>(searchAttrIdList);
        //封装成attrs
        List<SkuEsModel.Attrs> attrs = attrValueEntities.stream().filter(item -> {
            return attrIdSet.contains(item.getAttrId());
        }).map(item->{
            SkuEsModel.Attrs esAttrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, esAttrs);
            return esAttrs;
        }).collect(Collectors.toList());

        //hasStock向库存系统批量查询商品是否有库存
        Map<Long, Boolean> skuHasStockMap = null;
        try{
            List<Long> skuIds = upSkuInfos.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
            R skuHasStockR = wareFeignService.getSkuHasStock(skuIds);
            skuHasStockMap = parseSkuHasStockData(skuHasStockR).stream().collect(Collectors.toMap(SkuHasStockTo::getSkuId, SkuHasStockTo::getHasStock));
        }catch (Exception e){
            log.error("库存服务查询异常：原因{}", e);
        }


        //2.封装每个sku的信息
        Map<Long, Boolean> finalSkuHasStockMap = skuHasStockMap;
        List<SkuEsModel> collect = upSkuInfos.stream().map(sku -> {
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, esModel);
            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());
            //额外处理hasStock hotScore brandName brandImg catalogName
            //attrs id name val
            //TODO:是否有库存，如果没有查到就默认为有
            if(finalSkuHasStockMap == null){
                esModel.setHasStock(true);
            }else{
                esModel.setHasStock(finalSkuHasStockMap.get(sku.getSkuId()));
            }

            //热度评分 刚上架先放个0 这块自己扩展
            esModel.setHotScore(0L);
            //查询品牌和分类名字信息
            BrandEntity brand = brandService.getById(esModel.getBrandId());
            if(brand == null){
                esModel.setBrandName("未知品牌名");
            }else{
                esModel.setBrandName(brand.getName());
                esModel.setBrandImg(brand.getLogo());
            }
            CategoryEntity categoryEntity = categoryService.getById(esModel.getCatalogId());
            esModel.setCatalogName(categoryEntity.getName());
            esModel.setAttrs(attrs);
            return esModel;
        }).collect(Collectors.toList());

        // 将数据发送给es进行保存：gulimall-search
        R r = searchFeignService.productStatusUp(collect);
        if(r.getCode() == 0){
            //远程调用成功
            //修改当前spu的状态为已上架
            this.baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else{
            //远程调用失败
            //TODO 重复调用？接口幂等性：重试机制
            //Feign调用流程
            /**
             * 1、构建请求数据，将对象转为json
             *      RequestTemplate template = buildTemplateArgs.create(argv)
             * 2、发送请求进行执行（执行成功会解码相应数据）
             *      executeAndDecode(template);
             * 3、执行请求会有重试机制
             *      while(true){
             *          try{
             *              executeAndDecode(template);
             *          }catch(){
             *              try{
             *                  retryer.continueOrPropagate(e);
             *              }catch(){
             *                  throw ex;//重试器有异常会抛出
             *              }
             *
             *              continue;//没异常会继续重试
             *          }
             *      }
             */
        }
    }

    private List<SkuHasStockTo> parseSkuHasStockData(R r){
        List<SkuHasStockTo> ans = ((List<Map<String, Object>>) r.get("data")).stream().map(item -> {
            SkuHasStockTo skuHasStockTo = new SkuHasStockTo();
            skuHasStockTo.setHasStock((Boolean)item.get("hasStock"));
            // TODO 这个地方自动解析认为是integer，以后看看怎么办
            skuHasStockTo.setSkuId(((Integer)item.get("skuId")).longValue());
            return skuHasStockTo;
        }).collect(Collectors.toList());
        return ans;
    }
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String)params.get("key");
        String brandId = (String) params.get("brandId");
        String catelogId = (String) params.get("catelogId");
        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and(w -> w.eq("id", key).or().like("spu_name", key));
        }//这里之所以用and是为了表示and (id=? or spu_name like ?) and
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            queryWrapper.eq("brand_id", brandId);
        }
        if(!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)){
            queryWrapper.eq("catalog_id", catelogId);
        }
        if(!StringUtils.isEmpty(status)){
            queryWrapper.eq("publish_status", status);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }


}